package cn.fanyamin.web.struts;

import java.sql.Timestamp;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.validator.LazyValidatorForm;

import cn.fanyamin.business.BookService;
import cn.fanyamin.domain.BookSearchCriteria;
import cn.fanyamin.domain.UserCategory;
import cn.fanyamin.domain.User;
import cn.fanyamin.web.vo.BookVO;

public class BookAction extends SecureBaseAction {
    private static Log logger = LogFactory.getLog(AddressAction.class);
    private static int PAGE_SIZE = 40;

    public ActionForward list(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
        BookService bookService = getWebApp().getBookService();
           
        int pageNum = this.getPageNum(form);
        //User user = getUserFromSession(request);
        //setCategories(request, Category.CATEGORY_TYPE_BOOK);
        int cnt = bookService.getBookCount(null);
        int pageCount = cnt/PAGE_SIZE;
        if(cnt % PAGE_SIZE !=0) {
        	pageCount++;
        }
        List<BookVO> bookList = bookService.getAllBooks();
        request.setAttribute("bookList", bookList);

        request.setAttribute("pageNum", pageNum);
        request.setAttribute("pageCount", pageCount);
        logger.info("bookList: " + bookList);
        return new ActionForward("/WEB-INF/jsp/struts/tool/books.jsp");
    }
    
    public ActionForward find(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response) {
        BookService bookService = getWebApp().getBookService();
           
        BookSearchCriteria criteria = getSearchCriteriaFromForm(form);
        
        int categoryID = NumberUtils.toInt((String)request.getAttribute("categoryID"));
        if(categoryID > 0 ) {
        	criteria.setCategoryID(categoryID);
        }
        //User user = getUserFromSession(request);
        //setCategories(request, Category.CATEGORY_TYPE_BOOK);
        int pageNum = this.getPageNum(form);
        int cnt = bookService.getBookCount(criteria);
        int pageCount = cnt/PAGE_SIZE;
        if(cnt % PAGE_SIZE !=0) {
        	pageCount++;
        }
        logger.info("findbook: " + criteria);
        List<BookVO> bookList = bookService.listBook(pageNum,PAGE_SIZE, criteria );
        request.setAttribute("bookList", bookList);
        
        request.setAttribute("pageNum", pageNum);
        request.setAttribute("pageCount", pageCount);
        return new ActionForward("/WEB-INF/jsp/struts/tool/books.jsp");
    }
    
    public ActionForward create(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request, HttpServletResponse response) {
        BookService bookService = getWebApp().getBookService();
        BookVO vo = getBookFromForm(form);
        if(vo == null) {
            return mapping.findForward("failure");
        }
        try {
        	int bookID = bookService.createBook(vo);
        	vo.setBookID(bookID);
        } catch(Exception e) {
        	request.setAttribute("errorMessage", e.getMessage());
        	return add(mapping,form, request, response);
        }
        
        
        return list(mapping, form, request, response);
    }
    
    private int getPageNum(ActionForm form) {
        LazyValidatorForm bookForm = (LazyValidatorForm) form;
        return NumberUtils.toInt((String) bookForm.get("pageNum"));
    }
    private BookSearchCriteria getSearchCriteriaFromForm(ActionForm form) {
    	BookSearchCriteria vo = new BookSearchCriteria();
    	LazyValidatorForm bookForm = (LazyValidatorForm) form;
    	vo.setBookName((String) bookForm.get("bookName"));  
        vo.setBookSN((String) bookForm.get("bookSN")); 
        vo.setTags((String) bookForm.get("tags"));        
        vo.setStatus(NumberUtils.toInt((String) bookForm.get("status")));
        vo.setBorrower((String) bookForm.get("borrower"));
        vo.setCategoryID(NumberUtils.toInt((String) bookForm.get("categoryID")));
        vo.setDays(NumberUtils.toInt((String) bookForm.get("days")));
        return vo;
    }
    private BookVO getBookFromForm(ActionForm form) {
        BookVO vo = new BookVO();
        LazyValidatorForm bookForm = (LazyValidatorForm) form;

        vo.setBookID(NumberUtils.toInt((String) bookForm.get("bookID")));
        vo.setBookName((String) bookForm.get("bookName"));  
        vo.setBookSN((String) bookForm.get("bookSN")); 
        vo.setCategoryID(NumberUtils.toInt((String) bookForm.get("categoryID"))); 
        vo.setTags((String) bookForm.get("tags"));
        
        vo.setBorrowerName((String) bookForm.get("borrowerName"));
        vo.setBorrowerID(NumberUtils.toInt((String) bookForm.get("borrowerID")));
        vo.setBorrowLogID(NumberUtils.toInt((String) bookForm.get("borrowLogID")));
        String strBorrowDate = (String) bookForm.get("borrowDate");
        String strReturnDate = (String) bookForm.get("returnDate");
        if (StringUtils.isNotBlank(strBorrowDate)) {
        	vo.setBorrowDate(Timestamp.valueOf(strBorrowDate));
        }
        if (StringUtils.isNotBlank(strReturnDate)) {
        	vo.setReturnDate(Timestamp.valueOf(strReturnDate));
        }
        logger.info("getBookFromForm: " + vo);
        return vo;
    }

    public ActionForward retrieve(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request, HttpServletResponse response) {
        BookService bookService = getWebApp().getBookService();
        LazyValidatorForm bookFrom = (LazyValidatorForm)form;
        int BookID = NumberUtils.toInt((String)bookFrom.get("bookID"));
        BookVO book = bookService.retrieveBook(BookID);
        request.setAttribute("book", book);
        return new ActionForward("/WEB-INF/jsp/struts/tool/book.jsp");
    }
    
        
    public ActionForward update(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request, HttpServletResponse response) {
        
        BookService bookService = getWebApp().getBookService();
        BookVO vo = getBookFromForm(form);
        try {
        	int ret = bookService.updateBook(vo);
            logger.debug("update book " + ret + ", book=" + vo);
        } catch(Exception e) {
        	request.setAttribute("errorMessage", e.getMessage());
        	request.setAttribute("bookID", ""+vo.getBookID());
        	return edit(mapping,form, request, response);
        }
        
        return list(mapping, form, request, response);
    }
    
    public ActionForward delete(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request, HttpServletResponse response) {
        BookService bookService = getWebApp().getBookService();
        LazyValidatorForm bookFrom = (LazyValidatorForm)form;
        int bookID = NumberUtils.toInt((String)bookFrom.get("bookID"));
        bookService.deleteBook(bookID);
        logger.info("delete Book, bookID=" + bookID);
        //return mapping.findForward("success");
        return list(mapping, form, request, response);
    }
    
    public ActionForward add(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request, HttpServletResponse response) {
       
        setCategories(request, UserCategory.CATEGORY_TYPE_BOOK);
        
        return new ActionForward("/WEB-INF/jsp/struts/tool/book.jsp");
    }
    
    public ActionForward edit(ActionMapping mapping, ActionForm form,
                                HttpServletRequest request, HttpServletResponse response) {
        BookService bookService = getWebApp().getBookService();
        LazyValidatorForm BookFrom = (LazyValidatorForm)form;
        int bookID = NumberUtils.toInt((String)BookFrom.get("bookID"));
        if(bookID==0) {
        	bookID = NumberUtils.toInt((String)request.getAttribute("bookID"));
        }
        BookVO vo = bookService.retrieveBook(bookID);
        logger.debug("edit book: " + vo);
        request.setAttribute("book", vo);
        setCategories(request, UserCategory.CATEGORY_TYPE_BOOK);
        return new ActionForward("/WEB-INF/jsp/struts/tool/book.jsp");
    }
}
